package test230331;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/4/1 23:27
 */
public class Main11 {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt(); // 节点数
        int[] preorder = new int[n]; // 前序
        int[] inorder = new int[n]; // 中序
        for (int i = 0; i < inorder.length; i++) {
            inorder[i] = scan.nextInt();
        }
        for (int i = 0; i < preorder.length; i++) {
            preorder[i] = scan.nextInt();
        }
        TreeNode tree = buildTree(preorder, inorder); // 构造二叉树
        tree = reverseTree(tree);

        // 层次遍历
        StringBuilder res = new StringBuilder();
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.add(tree);
        while (!queue.isEmpty()) {
            TreeNode poll = queue.poll();
            res.append(poll.val + " ");
            if (poll.left != null) {
                queue.offer(poll.left);
            }
            if (poll.right != null) {
                queue.offer(poll.right);
            }
        }
        System.out.println(res.toString().trim());
        scan.close();
    }

    // 反转二叉树
    public static TreeNode reverseTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        reverseTree(root.left);
        reverseTree(root.right);
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        return root;
    }

    public static int i = 0; // 遍历前序序列

    // 根据前序和中序构造二叉树
    public static TreeNode buildTree(int[] preorder, int[] inorder) {
        return myBuildTree(preorder, inorder, 0, preorder.length - 1);
    }

    public static TreeNode myBuildTree(int[] preorder, int[] inorder, int start, int end){
        if(preorder == null || inorder == null){
            return null;
        }
        if(start > end){
            return null;
        }
        TreeNode root = new TreeNode(preorder[i]); // 新节点
        int indexForInorder = findIndex(inorder, preorder[i], start, end); // 根节点的位置
        i++;
        root.left = myBuildTree(preorder, inorder, start, indexForInorder - 1);
        root.right = myBuildTree(preorder, inorder, indexForInorder + 1, end);
        return root;
    }

    // 找到中序序列中的对应key
    public static int findIndex(int[] inorder, int key, int start, int end){
        for(int i = start; i <= end; ++i){
            if(inorder[i] == key){
                return i;
            }
        }
        return -1;
    }
}

class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
 }
